package com.woniu.controller;


import com.woniu.entity.Address;
import com.woniu.entity.User;
import com.woniu.service.AddressService;
import com.woniu.service.UserService;
import com.woniu.utils.CookieUtils;
import com.woniu.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author huangjianbin
 * @since 2023-02-07 11:59:16
 */
@RestController
@RequestMapping("/address")
public class AddressController {

    @Autowired
    AddressService addressService;

    @Autowired
    UserService userService;

    private User getCurrentUser(HttpServletRequest request){
        //获取已登录用户信息
        // 1.先从request拿到token
        // 2.从token获取到用户名
        // 3.根据用户名查询到用户信息
        String userTokenFromCookie = CookieUtils.getUserTokenFromCookie(request);
        String account = JwtUtils.getAccountWithoutException(userTokenFromCookie);

        return userService.getUserByUserName(account);
    }

    @PostMapping("add")
    public String add(String address, String tel, String name,HttpServletRequest request){
        User currentUser = getCurrentUser(request);
        addressService.addAddress(address,tel,name,currentUser.getId());

        return "ok";
    }

    @GetMapping("allOfCurrentUser")
    public List<Address> allOfCurrentUser(HttpServletRequest request){
        User currentUser = getCurrentUser(request);
        return addressService.allOfCurrentUser(currentUser.getId());
    }
}

